<script setup lang="ts">
import OneUpload from '@/components/oneUpload.vue';
import BusinessLicense from '@/assets/images/BusinessLicense.png';
import idcardBack from '@/assets/images/idcard_back.png';
import idcardFront from '@/assets/images/idcard_front.png';
import auth from '@/assets/images/auth.png';
import type { Enterprise } from 'vue';
import { addEnterpriceCertifcation, updateCertification, getLegalPerson } from '@/api/enterprise';
import { useDict } from '@/hooks/dict';
import { useNavTo } from '@/hooks/navTo';
import useEnterprise from '@/stores/enterprise';
const route = useRoute()
const { enterpriseType: enterpriseTypeOptions } = useDict('enterpriseType');
const { navTo } = useNavTo()
const handleType = ref('1')
import useUserStore from '@/stores/user';
const storeUser = useUserStore()
const tianbaoClose = () => {
  console.log(isAgree.value);
  if (!isAgree.value) {
    router.push({ path: '/' })
  }
}



// 表单数据
const form = reactive<Enterprise>({
  id: "",
  enterpriseName: '',
  creditCode: '',
  enterpriseNature: '',
  provinceSiteId: '',
  citySiteId: '',
  areaSiteId: '',
  legalAddress: '',
  corrProvinceSiteId: '',
  corrCitySiteId: '',
  corrAreaSiteId: '',
  corrAddress: '',
  registrationDate: '',
  businessTermType: '1',
  businessTermStart: '',
  businessTermEnd: '',
  businessScope: '',
  fileList: [
  ],
  legal: {
    name: '',
    idCard: '',
    cardBeginDate: '',
    cardEndDate: '',
    mobile: ''
  },
  operator: {
    name: '',
    idCard: '',
    cardBeginDate: '',
    cardEndDate: '',
    mobile: ''
  },
})


function legalAgentChange() {
  if (handleType.value === '1') {
    form.agentAuthFlag = null
    form.legalaAuthFlag = route.query.type
  } else {
    form.agentAuthFlag = route.query.type
    form.legalaAuthFlag = null
  }

  console.log("agentAuthFlag", form.agentAuthFlag);
  console.log("legalaAuthFlag", form.legalaAuthFlag);
}


// 身份证有效范围
const idCardTerm = computed({
  get() {
    if (form.legal.cardBeginDate && form.legal.cardEndDate) {
      return [form.legal.cardBeginDate, form.legal.cardEndDate]
    } else {
      return []
    }
  },
  set(val: []) {
    if (Array.isArray(val) && val.length > 1) {
      form.legal.cardBeginDate = val[0]
      form.legal.cardEndDate = val[1]
    } else {
      form.legal.cardBeginDate = ''
      form.legal.cardEndDate = ''
    }
  }
})
// 身份证有效范围
const idCardTermOperator = computed({
  get() {
    if (form.operator.cardBeginDate && form.operator.cardEndDate) {
      return [form.operator.cardBeginDate, form.operator.cardEndDate]
    } else {
      return []
    }
  },
  set(val: []) {
    if (Array.isArray(val) && val.length > 1) {
      form.operator.cardBeginDate = val[0]
      form.operator.cardEndDate = val[1]
    } else {
      form.operator.cardBeginDate = ''
      form.operator.cardEndDate = ''
    }
  }
})

// 经营时间范围
const operateTerm = computed({
  get() {
    if (form.businessTermStart && form.businessTermEnd) {
      return [form.businessTermStart, form.businessTermEnd]
    } else {
      return []
    }
  },
  set(val: []) {
    if (Array.isArray(val) && val.length > 1) {
      form.businessTermStart = val[0]
      form.businessTermEnd = val[1]
    } else {
      form.businessTermStart = ''
      form.businessTermEnd = ''
    }
  }
})
const storeEnter = useEnterprise()
const openTips = ref(false)
const isAgree = ref(false)

onMounted(() => {
  openTips.value = true
  const enterprise = storeEnter.getEnterprise()

  if (enterprise) {
    Object.assign(form, enterprise)

    getLegalPerson(form.id).then(res => {
      if (res.code === 200) {
        form.legal = res.data
      }
    })
  }

  storeEnter.clearEnterprise()
})


const disabled = ref(false)
// 提交认证数据
function submitCertification() {
  authRef.value.validate((valid) => {
    if (valid) {
      disabled.value = true
      if (form.id) {
        updateCertification(form).then(response => {
          if (response.code == 200) {
            ElMessage({
              message: '认证信息已提交，请耐心等待审核结果。',
              type: 'success'
            });
            storeUser.getInfo()
            setTimeout(() => {
              navTo('CompanyBack')

            }, 1500);
          } else {
            disabled.value = false
          }
          // 可以在这里处理提交成功后的逻辑，比如跳转到其他页面或显示提示信息
        }).catch(error => {
          disabled.value = false
          console.error('提交失败:', error);
          // 处理错误情况
        });
      } else {
        addEnterpriceCertifcation(form).then(response => {
          if (response.code == 200) {
            ElMessage({
              message: '认证信息已提交，请耐心等待审核结果。',
              type: 'success'
            });

            storeUser.getInfo()
            setTimeout(() => {
              navTo('CompanyBack')
            }, 1500);
          } else {
            disabled.value = false
          }
          // 可以在这里处理提交成功后的逻辑，比如跳转到其他页面或显示提示信息
        }).catch(error => {
          disabled.value = false
          console.error('提交失败:', error);
          // 处理错误情况
        });
      }
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
}
function regditArea(o) {
  console.log('区域数据变化:', o);
  form.provinceName = o.provinceName
  form.cityName = o.cityName
  form.areaName = o.areaName
}
function corrFinanceArea(o) {
  console.log('区域数据变化:', o);
  form.corrProvinceSiteName = o.provinceName
  form.corrCitySiteName = o.cityName
  form.corrAreaSiteName = o.areaName
}

// 上传图片
function handleUploadSuccess(type: string, url: string, mark: string) {
  form.fileList = form.fileList.filter(item => mark !== item.mark) // 移除之前的同类型文件
  form.fileList.push({
    fileType: type,
    fileUrl: url,
    mark
  })
}

// 校验规则方法
// 自定义校验身份证
const validateIdCard = (rule, value, callback) => {
  const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (!value || !idCardRegex.test(value)) {
    callback(new Error('请输入正确的18位身份证号码'));
  } else {
    callback();
  }
};

// 校验手机号
const validatePhone = (rule, value, callback) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!value || !phoneRegex.test(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
};

// 校验上传文件（如营业执照、身份证等）
const validateLicenseUpload = (rule, value, callback) => {
  if (licenseFilesStatus.value == 'error') {
    callback(new Error('请上传营业执照'));
  } else {
    callback();
  }
};
const validateoperatorUpload = (rule, value, callback) => {
  if (operatorFilesStatus.value == 'error') {
    callback(new Error('请上传经办人身份证正反面'));
  } else {
    callback();
  }
};
const validateauthUpload = (rule, value, callback) => {
  if (authFilesStatus.value == 'error') {
    callback(new Error('请上传授权查询协议'));
  } else {
    callback();
  }
};
const validatelegalUpload = (rule, value, callback) => {
  if (legalFilesStatus.value == 'error') {
    callback(new Error('请上传法人身份证正反面'));
  } else {
    callback();
  }
};

// 经办人身份证
const operatorFilesStatus = computed(() => {
  return form.fileList.filter(f => f.fileType === '3' || f.fileType === '2').length == 2 ? 'success' : 'error';
})
// 授权书
const authFilesStatus = computed(() => {
  return form.fileList.filter(f => f.fileType === '6').length == 3 ? 'success' : 'error';
})
// 法人身份证
const legalFilesStatus = computed(() => {
  return form.fileList.filter(f => f.fileType === '5' || f.fileType === '4').length == 2 ? 'success' : 'error';
})
// 校验营业执照
const licenseFilesStatus = computed(() => {
  return form.fileList.filter(f => f.fileType === '1').length == 1 ? 'success' : 'error';
})
const rules = reactive({
  enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  creditCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
  enterpriseNature: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
  areaSiteId: [{ required: true, message: '请选择注册所在区域', trigger: 'change' }],
  legalAddress: [{ required: true, message: '请输入注册地址', trigger: 'blur' }],
  corrAreaSiteId: [{ required: true, message: '请选择经营所在区域', trigger: 'change' }],
  corrAddress: [{ required: true, message: '请输入经营地址', trigger: 'blur' }],
  registrationDate: [{ required: true, message: '请选择成立日期', trigger: 'change' }],
  businessTermType: [{ required: true, message: '请选择营业期限', trigger: 'change' }],
  businessScope: [{ required: true, message: '请输入经营范围', trigger: 'blur' }],
  license: [{ required: true, validator: validateLicenseUpload, trigger: 'change' }],
  legalFiles: [{ required: true, validator: validatelegalUpload, trigger: 'change' }],
  'legal.name': [{ required: true, message: '请输入法定代表人姓名', trigger: 'blur' }],
  'legal.idCard': [{ required: true, validator: validateIdCard, trigger: 'blur' }],
  'legal.mobile': [{ required: true, validator: validatePhone, trigger: 'blur' }],
  'legal.termType': [{ required: true, message: '请选择法人身份证有效期', trigger: 'change' }],

  // 经办人校验（仅在 handleType === '2' 时需要）
  operatorFiles: [
    { required: true, validator: validateoperatorUpload, trigger: 'change' }
  ],
  'operator.name': [
    { required: true, message: '请输入经办人姓名', trigger: 'blur' }
  ],
  'operator.idCard': [
    { required: true, validator: validateIdCard, trigger: 'blur' }
  ],
  'operator.mobile': [
    { required: true, validator: validatePhone, trigger: 'blur' }
  ],
  'operator.termType': [
    { required: true, message: '请选择经办人身份证有效期', trigger: 'change' }
  ],

  authFiles: [
    { required: true, validator: validateauthUpload, trigger: 'change' }
  ]
})

const authRef = ref(null)

import api from "@/plugins/download.ts"
import router from '@/router';
//下载文件模板
function downloadFileTemplate() {
  api.template()
  // 这里是下载文件模板的逻辑
}
</script>
<template>
  <div>
    <el-radio-group v-model="handleType" @change="legalAgentChange">
      <el-radio value="1">我是法定代表人/经营者名称</el-radio>
      <el-radio value="2">我是经办人</el-radio>
    </el-radio-group>

    <div>
      <el-form :rules="rules" ref="authRef" :model="form" :label-width="220">
        <LeftTip className="mt-3" title="营业执照" />
        <el-form-item class="!items-start" label="营业执照照片：" prop="license" :validate-status="licenseFilesStatus">
          <OneUpload @uploadSuccess="handleUploadSuccess('1', $event, 'license')" class="!w-50 h-30"
            :backImgPath="BusinessLicense" />
        </el-form-item>

        <el-form-item label="企业/个体工商户名称：" prop="enterpriseName">
          <el-input size="large" placeholder="请输入企业或个体工商户名称" v-model="form.enterpriseName" />
        </el-form-item>

        <el-form-item label="统一社会信用代码：" prop="creditCode">
          <el-input size="large"  placeholder="请输入统一社会信用代码" maxLength="18" show-overflow
            v-model="form.creditCode" />
        </el-form-item>

        <el-form-item label="企业类型：" prop="enterpriseNature">
          <el-select size="large" v-model="form.enterpriseNature" placeholder="请选择企业类型">
            <el-option v-for="(item, i) in enterpriseTypeOptions" :label="item.label" :key="i"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="注册所在区域：" prop="areaSiteId">
          <cityChoose v-model:provinceSiteId="form.provinceSiteId" @dataChange="regditArea"
            v-model:citySiteId="form.citySiteId" v-model:areaSiteId="form.areaSiteId" />
        </el-form-item>

        <el-form-item label="注册地址：" prop="legalAddress">
          <el-input size="large" placeholder="请输入详细注册地址" v-model="form.legalAddress" />
        </el-form-item>

        <el-form-item label="经营所在区域：" prop="corrAreaSiteId">
          <cityChoose v-model:provinceSiteId="form.corrProvinceSiteId" v-model:citySiteId="form.corrCitySiteId"
            v-model:areaSiteId="form.corrAreaSiteId" @dataChange="corrFinanceArea" />
        </el-form-item>

        <el-form-item label="经营地址：" prop="corrAddress">
          <el-input size="large" placeholder="请输入详细经营地址" v-model="form.corrAddress" />
        </el-form-item>

        <el-form-item label="成立日期：" prop="registrationDate">
          <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="form.registrationDate" class="!w-full"
            type="date" placeholder="请选择成立日期" size="large" />
        </el-form-item>

        <el-form-item label="营业期限：" prop="businessTermType">
          <el-select v-model="form.businessTermType" class="!w-30" size="large" placeholder="请选择营业期限">
            <el-option label="长期" value="1"></el-option>
            <el-option label="短期" value="2"></el-option>
          </el-select>
          <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-if="form.businessTermType === '2'"
            v-model="operateTerm" class="flex-1 ml-2" type="daterange" range-separator="To" start-placeholder="开始时间"
            end-placeholder="结束时间" size="large" />
        </el-form-item>

        <el-form-item class="!items-start" label="经营范围：" prop="businessScope">
          <el-input type="textarea" size="large" placeholder="请输入企业的经营范围" v-model="form.businessScope" />
        </el-form-item>

        <LeftTip className="mt-3" title="法定代表人/经营者" />
        <el-form-item class="!items-start" label="身份证正反面：" prop="legalFiles" :validate-status="legalFilesStatus">
          <div>
            <OneUpload @uploadSuccess="handleUploadSuccess('4', $event, 'legafront')" class="!w-50 h-30"
              :backImgPath="idcardFront" />
            <p class="mt-1 text-4.5">身份证人像面</p>
          </div>
          <div class="ml-3">
            <OneUpload @uploadSuccess="handleUploadSuccess('5', $event, 'legaback')" class="!w-50 h-30"
              :backImgPath="idcardBack" />
            <p class="mt-1 text-4.5">身份证国徽面</p>
          </div>
        </el-form-item>

        <el-form-item label="姓名：" prop="legal.name">
          <el-input size="large" placeholder="请输入您的真实姓名" v-model="form.legal.name" />
        </el-form-item>

        <el-form-item label="身份证号：" prop="legal.idCard">
          <el-input size="large" maxlength="20" show-word-limit placeholder="请输入18位身份证号码" v-model="form.legal.idCard" />
        </el-form-item>

        <el-form-item label="身份证有效期：" prop="legal.termType">
          <el-select v-model="form.legal.termType" class="!w-30" size="large" placeholder="请选择有效期">
            <el-option label="长期" value="1"></el-option>
            <el-option label="短期" value="2"></el-option>
          </el-select>
          <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-if="form.legal.termType === '2'"
            v-model="idCardTerm" class="flex-1 ml-2" type="daterange" range-separator="To" start-placeholder="开始时间"
            end-placeholder="结束时间" size="large" />
        </el-form-item>

        <el-form-item label="手机号：" prop="legal.mobile">
          <el-input size="large" placeholder="请输入您的手机号码" :maxlength="11" show-word-limit v-model="form.legal.mobile" />
        </el-form-item>

        <div v-if="handleType === '2'">
          <LeftTip className="mt-3" title="经办人信息" />
          <el-form-item class="!items-start" label="身份证正反面：" :validate-status="operatorFilesStatus"
            prop="operatorFiles">
            <div>
              <OneUpload class="!w-50 h-30" @uploadSuccess="handleUploadSuccess('2', $event, 'front')"
                :backImgPath="idcardFront" />
              <p class="mt-1 text-4.5">身份证人像面</p>
            </div>
            <div class="ml-3">
              <OneUpload class="!w-50 h-30" @uploadSuccess="handleUploadSuccess('3', $event, 'back')"
                :backImgPath="idcardBack" />
              <p class="mt-1 text-4.5">身份证国徽面</p>
            </div>
          </el-form-item>
          <el-form-item label="姓名：" prop="operator.name">
            <el-input size="large" placeholder="请输入您的真实姓名" v-model="form.operator.name" />
          </el-form-item>
          <el-form-item label="身份证号：" prop="operator.idCard">
            <el-input size="large" maxlength="20" show-word-limit placeholder="请输入18位身份证号码"
              v-model="form.operator.idCard" />
          </el-form-item>
          <el-form-item label="身份证有效期：" prop="operator.termType">
            <el-select v-model="form.operator.termType" class="!w-30" size="large" placeholder="请选择有效期">
              <el-option label="长期" value="1"></el-option>
              <el-option label="短期" value="2"></el-option>
            </el-select>
            <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-if="form.operator.termType === '2'"
              v-model="idCardTermOperator" class="flex-1 ml-2" type="daterange" range-separator="To"
              start-placeholder="开始时间" end-placeholder="结束时间" size="large" />
          </el-form-item>
          <el-form-item label="手机号：" prop="operator.mobile">
            <el-input size="large" placeholder="请输入您的手机号码" :maxlength="11" show-word-limit
              v-model="form.operator.mobile" />
          </el-form-item>
        </div>

        <el-form-item class="!items-start" label="授权查询协议：" prop="authFiles" :validate-status="authFilesStatus">
          <OneUpload class="!w-38 h-28" @uploadSuccess="handleUploadSuccess('6', $event, 'one')" :backImgPath="auth" />
          <OneUpload class="!w-38 h-28" @uploadSuccess="handleUploadSuccess('6', $event, 'two')" :backImgPath="auth" />
          <OneUpload class="!w-38 h-28" @uploadSuccess="handleUploadSuccess('6', $event, 'three')"
            :backImgPath="auth" />
          <a href="javascript:void(0);" @click="downloadFileTemplate" style="writing-mode:vertical-lr">下载模板</a>
        </el-form-item>
        <el-form-item>
          <div class="mb3"> 下载 <span @click="downloadFileTemplate" class="cursor-pointer">《信易贷授权查询协议》</span>
            模板并根据要求填写内容，加盖公章后拍照上传。</div>
          <el-button type="primary" size="large" :disabled="disabled" @click="submitCertification"
            class="w-1.2/3">立即提交</el-button>
          <el-button class="w-1.2/3" size="large">保存草稿</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog title="企业填报信息承诺书" @close="tianbaoClose" center v-model="openTips" width="800px">
      <div class="text-4.5 p-3">
        <p>本单位郑重承诺：</p>
        <p class="mt-2">1、在平台上自主填报的各项信息均合法、真实、准确和有效，无任何伪造和虚假成分，对所提供资料的真实性负责，若三次填报信息均与真实信息不符，属于违反信用承诺。</p>
        <p class="mt-1">2、严格遵守国家法律、法规、规章和政策规定，依法经营，重信守诺，维护良好的企业信用记录。</p>
        <p class="mt-1">3、如发生信息造假或承诺失信，依照有关法律、行政法规规定自愿接受有关部门给予的行政处罚、约束和失信惩戒，依法承担相应责任。</p>
        <p class="mt-1">4、同意本《信用承诺书》通过“信用中国” 网站向社会公开接受社会监督。</p>
      </div>
      <template #footer>
        <div class="pb-7 mt-3">
          <el-button type="primary" class="w-50 !text-4.5 !h-10"
            @click="openTips = false, isAgree = true">我已阅读并同意</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
@use '@/assets/styles/el_form.scss'
</style>
